package top.zhmq.demo.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.zhmq.demo.domain.Authority;
import top.zhmq.demo.domain.Customer;
import top.zhmq.demo.repository.AuthorityRepository;
import top.zhmq.demo.repository.CustomerRepository;

import java.util.List;

/**
 * TODO 在此处添加描述
 *
 * @author Glory
 * @classname CustomerService
 * @create 2021-04-26 10:27
 */

@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private AuthorityRepository authorityRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    // 业务控制：使用唯一用户名查询用户信息，若用户信息在redis中有缓存，则直接使用，否则从数据库查询并存入redis
    public Customer getCustomer(String username) {
        Customer customer;
        Object o = redisTemplate.opsForValue().get("customer_" + username);
        if (o != null) {
            customer = (Customer) o;
        } else {
            customer = customerRepository.findByUsername(username);
            if (customer != null) {
                redisTemplate.opsForValue().set("customer_" + username, customer);
            }
        }
        return customer;
    }

    // 业务控制：使用唯一用户名查询用户权限，若用户权限信息在redis中有缓存，则直接使用，否则从数据库查询并存入redis
    public List<Authority> getCustomerAuthority(String username) {
        List<Authority> authorities;
        Object o = redisTemplate.opsForValue().get("authorities_" + username);
        if (o != null) {
            authorities = (List<Authority>) o;
        } else {
            authorities = authorityRepository.findAuthoritiesByUsername(username);
            if (authorities.size() > 0) {
                redisTemplate.opsForValue().set("authorities_" + username, authorities);
            }
        }
        return authorities;
    }

    public void registerCustomer(Customer customer,List<Authority> authorities){
        customerRepository.save(customer);
        authorityRepository.saveAll(authorities);
    }
}

